﻿using System;
using Ninject;
using PgBirdie.Console.Command;
using PgBirdie.Core.Config;
using PgBirdie.Core.Error;
using PgBirdie.Core.Extensions;
using PgBirdie.Core.Helpers;
using PgBirdie.Core.Model;

namespace PgBirdie.Console
{
    class Program
    {
        private static int Main(string[] args)
        {
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
#endif

            IKernel kernel = new StandardKernel(new ServiceModule());

            return new Program().Run(kernel, args).ToNumeric();
        }

        private ExitCodeType Run(IKernel kernel, string[] args)
        {
            CommandType commandType;
            if (!ValidateArguments(args, out commandType))
            {
                AppConsole.WriteLine("Available commands:");
                AppConsole.WriteLine("Dump [PathToConfig.xml]");
                AppConsole.WriteLine("Delta [PathToConfig.xml]");
                //AppConsole.WriteLine("Restore [PathToConfig.xml]");
                return ExitCodeType.Failure;
            }

            if (Settings.PopulateFromConfigFile(commandType, args[1]) == ExitCodeType.Failure)
                return ExitCodeType.Failure;

            switch (commandType)
            {
                case CommandType.Delta: return kernel.Get<ICommand>("Delta").Run();
                case CommandType.Dump: return kernel.Get<ICommand>("Dump").Run();
                case CommandType.Restore: return kernel.Get<ICommand>("Restore").Run();
                default: throw new ArgumentException("Could not validate given arguments.");
            }
        }

        private bool ValidateArguments(string[] args, out CommandType commandType)
        {
            if (args.Length == 2)
            {
                var command = args[0];

                if (command.Equals("delta", StringComparison.OrdinalIgnoreCase))
                {
                    commandType = CommandType.Delta;
                    return true;
                }
                if (command.Equals("dump", StringComparison.OrdinalIgnoreCase))
                {
                    commandType = CommandType.Dump;
                    return true;
                }
            }

            commandType = CommandType.Undefined;
            return false;
        }

        private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is PgBirdieException)
                AppConsole.WriteLine(((PgBirdieException)e.ExceptionObject).Message);
            else
                AppConsole.WriteLine(e.ExceptionObject.ToString());
            System.Console.WriteLine(Environment.NewLine + "Press any key to continue");
            System.Console.ReadLine();
            Environment.Exit(1);
        }
    }
}